<?php
 /**
   * This program is free software; you can redistribute it and/or
   * modify it under the terms of the GNU General Public License
   * as published by the Free Software Foundation; either version 2
   * of the License, or any later version.
   *
   * This program is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   * GNU General Public License for more details.
   *
   * You should have received a copy of the GNU General Public License
   * along with this program; if not, write to the Free Software
   * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
   *
   * ----------------------------------------------------------------------
   * NimWiki - designer centric wiki
   *
   * @author Nicolas Myers <myers.nicolas@gmail.com>
   * @copyright 2007 Nicolas Myers
   * @version 0.9.0
   * @link
   * ----------------------------------------------------------------------
   * MEDIAMGR.PHP
   *
   * Mediamanager file
   * ----------------------------------------------------------------------
   */

    $requestWhat = empty($_REQUEST["what"]) ? "" : $_REQUEST["what"];
    switch ($requestWhat) {
       /*
        * Ajax call : gets the file list and displays thumbnails
        */
        case "filelist":
            $handle = opendir($cfg["media_dir"]);
            $forbid = array(".", "..", "Thumbs.db", "thumbs");
            while ($file = readdir($handle)) {
                if(!in_array($file, $forbid)) {
                    $thumbFile=makeThumb($cfg['media_dir'].$file);
                    echo '<div class="vignette" style="background-image:url(\''.$thumbFile.'\')" title="'.$file.'" ><span style="display:none" >'.$file.'</span></div>';
                }
            }
            break;
       /*
        * Ajax call : gets the file list and displays thumbnails
        */
        case "uploaded":
              if(isset($_POST['upload'])) {
                  $content_dir = $cfg["media_dir"];
                  $tmp_file = $_FILES['fichier']['tmp_name'];
                  if(!is_uploaded_file($tmp_file)) die("pbm");
                  $regexMedia = "/(.jpg|.gif|.png|.swf|.mov|.mp3)$/";
                  if (preg_match($regexMedia,$_FILES['fichier']['name'],$matches)) {
                      // on copie le fichier dans le dossier de destination
                      $newfilename = $content_dir . normalizeStr(substr($_FILES['fichier']['name'], 0, -4)) . $matches[1];
                      if (!move_uploaded_file($tmp_file, $newfilename)) {
                        $message = "Can't copy uploaded file in $content_dir";
                      } else {
                          //post traitement
                          switch ($matches[1]) {
                          case ".jpg":
                          case ".gif":
                          case ".png":
                                resizeImage($newfilename, $newfilename, $cfg["maxWidth"], $cfg["maxHeight"]);
                                break;
                          case ".swf":
                                break;
                          case ".mp3":
                                break;
                          case ".mov":
                                break;
                          default:
                                break;
                          }
                      }
                  } else {
                      die ("This filetype is not valid :".$_FILES['fichier']['name']);
                  }
                  echo "<script>window.parent.updateList();</script>";
              } else {
                  die("pbm upl");
              }
              break;
       /*
        * Ajax call : gets the file list and displays thumbnails
        */
        case "delimage":
            $filetodel = basename($_REQUEST['id']);
            unlink($cfg["media_dir"] . $filetodel);
            unlink($cfg["media_dir"] . '/thumbs/thumb_' . $filetodel);
            echo "<script>window.parent.updateList();</script>";
            break;
       /*
        * Ajax call : gets the file list and displays thumbnails
        */
        default:
            $message = "";
            $output = array();
            $output['message'] = "";
            outputPage($output, $cfg["tpl_dir"] . $cfg["tpl_media_mgr"]);
            break;
    }

   /**
    * Makes a thumbnail (uses GD lib)
    * @param  string $file image filename
    * @return string thumbnail filename
    */
    function makeThumb($file)
    {
      global $cfg;
      $images_ext = array("jpg", "jpeg", "gif", "png");
      if (file_exists($file)) {
          $fileinfo = pathinfo($file);
          if (@in_array($fileinfo['extension'], $images_ext)) {
              $imagefile = $file;
              $thumbfile = $fileinfo['dirname'] . '/thumbs/thumb_' . $fileinfo['basename'];
              if (!file_exists($thumbfile)) {
                  resizeImage($imagefile, $thumbfile, 100, 100);
              }
              return $thumbfile;
          } else {
              if(@file_exists($cfg["rsrc_dir"] . "filetype/" . $fileinfo['extension'] . ".gif"))
                  return $cfg["rsrc_dir"] . "filetype/" . $fileinfo['extension'] . ".gif";
              else
                  return $cfg["rsrc_dir"] . "filetype/undefined.gif";
          }
      } else {
          return "doesnotexist.gif";
      }
      
    }

   /**
    * Resizes an image and create a jpeg file
    * the produced image fits in the (widthMax x heightMax) box
    * @param  string  $sourcefile  image filename
    * @param  string  $destfile    destination filename
    * @param  int     $widthMax    
    * @param  int     $heightMax
    * @param  int     $quality
    * 
    * @todo resize images <> than jpg
    */
    function resizeImage($sourcefile, $destfile, $widthMax, $heightMax, $quality = 80)
    {
        list($width, $height) = GetImageSize($sourcefile);
        $ratioImage = $width / $height;
        $ratioCadre = $widthMax / $heightMax;
        if ($ratioImage > $ratioCadre) {
            //image plus horizontale que la boite
            $newWidth = $widthMax;
            $newHeight = ceil($widthMax / $ratioImage);
        } else {
            //image plus verticale que la boite
            $newHeight = $heightMax;
            $newWidth = ceil($heightMax * $ratioImage);
        }
        
        $src = imagecreatefromjpeg($sourcefile);
        $dst = imagecreatetruecolor($newWidth, $newHeight);
        imagecopyresampled($dst, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
        imagejpeg($dst, $destfile, $quality);
        imagedestroy($src);
        imagedestroy($dst);
    }
?>
